package com.im.tcp.register;

import com.im.tcp.config.TcpConfig;
import com.im.common.constant.Constants;
import com.im.tcp.utils.ZkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.InetAddress;

/**
 * 此类表示用于在Zookeeper中注册服务器IP和端口信息
 */
@Slf4j
@Component
@DependsOn({"limServer", "limWebSocketServer"})
public class RegistryZK {

    @Autowired
    private ZooKeeper zKClient;
    @Autowired
    private ZkUtil zkUtil;
    @Autowired
    private TcpConfig nettyConfig;

    @PostConstruct
    public void init() throws Exception {
        // 创建Zookeeper中的根节点
        createRootNode();
        // 获取本地主机地址
        String ip = InetAddress.getLocalHost().getHostAddress();
        // 创建服务器TCP配置的节点
        String tcpPath = Constants.ImCoreZkRoot + Constants.ImCoreZkRootTcp + "/" + ip + ":" + nettyConfig.getTcpPort();
        zkUtil.createNode(tcpPath);
        log.info("注册Zookeeper TCP路径成功，msg=[{}]", tcpPath);

        // 创建服务器WebSocket配置的节点
        String webPath = Constants.ImCoreZkRoot + Constants.ImCoreZkRootWeb + "/" + ip + ":" + nettyConfig.getWebSocketPort();
        zkUtil.createNode(webPath);
        log.info("注册Zookeeper WebSocket路径成功，msg=[{}]", webPath);
    }

    /**
     * 创建 ZooKeeper 的根节点以及其子节点，例如 "im-coreRoot/tcp/ip:port"
     */
    public void createRootNode() {
        // 判断 im-coreRoot 节点是否存在，不存在则创建
        boolean exists = zkUtil.exists(Constants.ImCoreZkRoot);
        if (!exists) {
            zkUtil.createNode(Constants.ImCoreZkRoot);
        }
        // 判断 im-coreRoot/tcp 节点是否存在，不存在则创建
        boolean tcpExists = zkUtil.exists(Constants.ImCoreZkRoot + Constants.ImCoreZkRootTcp);
        if (!tcpExists) {
            zkUtil.createNode(Constants.ImCoreZkRoot + Constants.ImCoreZkRootTcp);
        }
        // 判断 im-coreRoot/web 节点是否存在，不存在则创建
        boolean webExists = zkUtil.exists(Constants.ImCoreZkRoot + Constants.ImCoreZkRootWeb);
        if (!webExists) {
            zkUtil.createNode(Constants.ImCoreZkRoot + Constants.ImCoreZkRootWeb);
        }
    }
}
